package com.xiaoxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxx.common.error.ErrorException;
import com.xiaoxx.common.result.RType;
import com.xiaoxx.mapper.ChatApikeyMapper;
import com.xiaoxx.mapper.ChatModelMapper;
import com.xiaoxx.model.dto.chat.ChatApiKeyDto;
import com.xiaoxx.model.entity.chat.ChatApikey;
import com.xiaoxx.model.entity.chat.ChatModel;
import com.xiaoxx.model.vo.chat.ChatApiKeyVo;
import com.xiaoxx.service.ChatApikeyService;
import com.xiaoxx.utils.BeanDtoVoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HX
 * @since 2024-05-17
 */
@Service
public class ChatApikeyServiceImpl extends ServiceImpl<ChatApikeyMapper, ChatApikey> implements ChatApikeyService {

    @Autowired
    private ChatModelMapper chatModelMapper;

    @Override
    public Boolean addChatApikey(ChatApiKeyDto chatApiKeyDto) {
        return save(BeanDtoVoUtil.convert(chatApiKeyDto, ChatApikey.class));

    }

    @Override
    public Boolean updChatApikey(ChatApiKeyDto chatApiKeyDto) {
        ChatApikey convert = BeanDtoVoUtil.convert(chatApiKeyDto, ChatApikey.class);
        return updateById(convert);
    }

    @Override
    public List<ChatApiKeyVo> getList(Integer status) {
        List<ChatApikey> chatApikeys = baseMapper.selectList(new LambdaQueryWrapper<ChatApikey>()
                .eq(status != null, ChatApikey::getStatus, status));
        return BeanDtoVoUtil.listVo(chatApikeys, ChatApiKeyVo.class);
    }

    @Override
    public Boolean updStatus(String id) {
        ChatApikey chatApikey = baseMapper.selectById(id);
        if (chatApikey == null) {
            throw new ErrorException(RType.SYS_ERROR_CODE_500);
        }

        if (chatApikey.getStatus() == 1) {
            //未使用
            update(new LambdaUpdateWrapper<ChatApikey>()
                    .set(ChatApikey::getStatus, 2)
                    .eq(ChatApikey::getId, id));
        } else {
            //使用中
            update(new LambdaUpdateWrapper<ChatApikey>()
                    .set(ChatApikey::getStatus, 1)
                    .eq(ChatApikey::getId, id));
        }
        return true;

    }

    @Override
    public Boolean del(String id) {
        Integer count = chatModelMapper.selectCount(new LambdaQueryWrapper<ChatModel>()
                .eq(ChatModel::getApikeyId, id));
        if (count > 0) {
            throw new ErrorException(500, "该ApiKey正在使用，无法删除");
        }
        return removeById(id);
    }

}
